import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-05-27
 * Time: 19:33
 */

class TreeNode {
      int val;
     TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }


class Solution {
    //在中序数组里面找到根节点的位置
    public int preIndex = 0;
    private int inOrderIndex(int[] preorder,int preIndex,int[] inorder){
        for(int i =0;i<inorder.length;++i){
            if(preorder[preIndex]==inorder[i]){
                return i;
            }
        }
        return -1;
    }

    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inEnd){
        if(inEnd<inbegin) return null;
        //创建头结点
        TreeNode root = new TreeNode(preorder[preIndex]);
        int rootIndex = inOrderIndex(preorder,preIndex,inorder);
        preIndex++;
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,inbegin+1,inEnd);
        return root;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }
}
class Solution3 {
    public List<Integer> preorderTraversal(TreeNode root) {
        //整不清楚走到空的时候要不要弹出来
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }
}
public class TestDemo {


    public static void main(String[] args) {
        Solution3 solution3 = new Solution3();
        TreeNode node1 = new TreeNode(1);

        solution3.preorderTraversal(node1);
    }
    public static void main2(String[] args) {
        Solution solution = new Solution();
//        输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
//        输出: [3,9,20,null,null,15,7]
        int[] preorder = {3,9,20,15,7};
        int[] inorder = {9,3,15,20,7};
        solution.buildTree(preorder,inorder);
    }
}
